﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using MayhemCore;
using SensorHOL;
using Microsoft.WindowsAPICodePack.Sensors;

namespace SensorMayhem.Events
{
    [DataContract]
    [MayhemModule("Sensor: Free Fall", "Triggers when the computer is in free fall")]
    public class FreeFall : EventBase
    {

        SensorHelper<Accelerometer3D, Acceleration3D> accelerometerSensor;

        private bool triggered = false;

        protected override void OnEnabling(EnablingEventArgs e)
        {
            try
            {
                accelerometerSensor = new SensorHelper<Accelerometer3D, Acceleration3D>();
                accelerometerSensor.Initialize();
                accelerometerSensor.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(accelerometerSensor_PropertyChanged);
            }
            catch (Exception)
            {

            }

        }

        void accelerometerSensor_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            var a3d = accelerometerSensor.Value as Acceleration3D;
            if (a3d != null)
            {
                float x = a3d[AccelerationAxis.XAxis];
                float y = a3d[AccelerationAxis.YAxis];
                float z = a3d[AccelerationAxis.ZAxis];

                bool trigger = IsFreeFall(x, y, z);
                if (trigger && !triggered)
                {
                    Trigger();
                }
                else if (!trigger)
                {
                    ResetTrigger();
                }
            }
        }

        bool IsFreeFall(float x, float y, float z)
        {
            if (Math.Abs(x) < 0.01 && Math.Abs(y) < 0.01 && Math.Abs(z) < 0.01)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        void ResetTrigger()
        {
            triggered = false;
        }

        protected override void OnDisabled(DisabledEventArgs e)
        {
            try
            {
                accelerometerSensor.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(accelerometerSensor_PropertyChanged);
            }
            catch (Exception)
            {

            }
            ResetTrigger();
        }

    }
}
